package cn.codeartist.springboot.component.dynamic.aop;

import cn.codeartist.springboot.component.dynamic.annotation.DB;
import cn.codeartist.springboot.component.dynamic.druid.DynamicDataSourceHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.AnnotationUtils;

/**
 * 动态数据源切片
 *
 * @author 艾江南
 * @date 2019/3/30
 */
@Aspect
public class DynamicDataSourceAspect {

    /**
     * 环绕执行
     *
     * @param joinPoint 切点
     * @throws Throwable 异常
     */
    @Around("@within(db) || @annotation(db)")
    public Object doAround(ProceedingJoinPoint joinPoint, DB db) throws Throwable {
        if (db == null) {
            db = AnnotationUtils.findAnnotation(joinPoint.getClass(), DB.class);
        }
        if (db == null) {
            return joinPoint.proceed();
        }
        try {
            DynamicDataSourceHolder.setDbType(db.value());
            return joinPoint.proceed();
        } finally {
            DynamicDataSourceHolder.resetDbType();
        }
    }
}
